package cn.touna.jss.modules.custom.tongduncoinfig;

import cn.touna.jss.modules.credit.entity.TongDunConfigEntity;
import cn.touna.jss.modules.credit.mapper.TongDunConfigEntityMapper;
import cn.touna.risk.cache.redis.RedisCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 同盾配置信息
 */
@Service
public class TongDunConfigService {

    private static final Logger logger = LogManager.getLogger(TongDunConfigService.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TongDunConfigEntityMapper tongDunConfigEntityMapper;

    /**
     * 读取数据库中同盾配置信息到Redis中
     */
    @PostConstruct
    public void readConfigToRedis(){

        //从数据库中查询同盾的配置信息
        List<TongDunConfigEntity> configList = tongDunConfigEntityMapper.queryAll();
        AtomicInteger count = new AtomicInteger(0);
        if (!CollectionUtils.isEmpty(configList)) {
            Iterator var3 = configList.iterator();
            while(var3.hasNext()) {
                TongDunConfigEntity tdConfig = (TongDunConfigEntity) var3.next();
                String key = String.format("TongDunConfig:%s:%s:%s", tdConfig.getProductType(), tdConfig.getPlatform(), tdConfig.getEventType());
                this.redisCache.set(key, tdConfig);
                count.incrementAndGet();
            }
            logger.info("同盾配置信息初始化加载完毕，num:{}", count.getAndIncrement());
        }
    }

    /**
     * 从Redis中获取TongDunConfigEntity对象
     * @param productType
     * @param platform
     * @param eventType
     * @return
     */
    public TongDunConfigEntity getTongDunConfigEntity(String productType, String platform, String eventType){
        String key = String.format("TongDunConfig:%s:%s:%s", new Object[]{productType, platform, eventType});
        TongDunConfigEntity entity =  (TongDunConfigEntity)this.redisCache.get(key);
        return entity;
    }

}
